package com.SmartCare.service.impl.health;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.SmartCare.common.Result;
import com.SmartCare.service.health.BodyWeightService;
import com.SmartCare.common.vo.health.BodyWeightVo;
import com.SmartCare.mapper.health.BodyWeightMapper;
import com.SmartCare.pojo.health.BodyWeight;
import com.SmartCare.utils.DateTimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class BodyWeightServiceImpl extends ServiceImpl<BodyWeightMapper, BodyWeight> implements BodyWeightService {
    /**
     * 体重记录添加
     */
    @Override
    public Result weightAdd(Long elderlyId, Float bodyWeight) {
        if (elderlyId==null) {
            return Result.error("未知错误");
        }else if(!(bodyWeight>0)){
            return Result.error("数据输入错误");
        }

        //更新数据
        BodyWeight one = BodyWeight.builder()
                .elderlyId(elderlyId)
                .weight(bodyWeight)
                .build();
        boolean res = save(one);
        if (!res) {
            return Result.error("添加失败");
        }
        return Result.success("添加成功");
    }

    /**
     * 查询体重记录
     */
    @Override
    public Result bodyWeightQueryWeek(Long elderlyId, String startTime, String endTime) {

        LambdaQueryWrapper<BodyWeight> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BodyWeight::getElderlyId,elderlyId);
        wrapper.between(BodyWeight::getCreatedTime,startTime,endTime);
        wrapper.orderByAsc(BodyWeight::getCreatedTime);
        List<BodyWeight> list = list(wrapper);
        if (list.isEmpty()) {
            return Result.error("无记录");
        }
        List<BodyWeightVo> res= new ArrayList<>();
        list.forEach((item)->{
            BodyWeightVo vo = new BodyWeightVo();
            BeanUtils.copyProperties(item,vo,"createdTime");
            vo.setCreatedTime(DateTimeUtils.formatDateTime(item.getCreatedTime()));
            res.add(vo);
        });
        return Result.success(res);
    }
}
